package com.loveprogrammer.redismq.listener.handler;

import com.loveprogrammer.redismq.annotation.Listeners;
import lombok.extern.slf4j.Slf4j;
import org.reflections.Reflections;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * @ClassName HandlerFactory
 * @Description 监听器工厂
 * @Author admin
 * @Date 2023/10/16 11:21
 * @Version 1.0
 */
@Component
@Slf4j
public class HandlerFactory implements CommandLineRunner {

    public Map<String, Class> handlerMap = new HashMap<>();

    @Override
    public void run(String... args) throws Exception {
        // 找到所有实现类
        Reflections reflections = new Reflections("com.loveprogrammer.redismq.listener.handler.impl");
        // 获取在指定包扫描的目录所有的实现类
        Set<Class<? extends BaseHandler>> classes = reflections.getSubTypesOf(BaseHandler.class);
        for (Class<? extends IHandler > aClass : classes) {
            try {
                Listeners listeners = aClass.getAnnotation(Listeners.class);
                String topic = listeners.topic();
                handlerMap.put(topic, aClass);
                log.info("初始化监听器成功 {}",aClass.getName());
            } catch (Exception e) {
                log.error("初始化" + aClass.getName() + "监听器失败",e);
            }
        }
    }
}
